package com.cn.xcsharp.filter;

import com.cn.xcsharp.util.CommonResult;
import com.cn.xcsharp.util.JwtUtil;
import com.cn.xcsharp.util.StrDbUtils;
import com.cn.xcsharp.util.StrUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token验证拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{
            // 从 http 请求头中取出 token
            String token = request.getHeader("token");
            // 如果不是映射到方法直接通过
            if(!(handler instanceof HandlerMethod)){
                return true;
            }
            if (token != null){
                String username = JwtUtil.getUserNameByToken(request);
                // 这边拿到的 用户名 应该去数据库查询获得密码，简略，步骤在service直接获取密码
                boolean result = JwtUtil.verify(token,username, StrDbUtils.getPassword(username));
                if(result){
//                    System.out.println("通过拦截器");
                    return true;
                }
            }
        }catch (Exception e){

        }
        falseResult(response);
        return false;
    }
    public void falseResult(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        CommonResult result = new CommonResult();
        result.setState(601);
        result.setMsg(StrUtils.INFO_601);
        ObjectMapper objectMapper = new ObjectMapper();
        response.getWriter().println(objectMapper.writeValueAsString(result));
        return;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
